import 'dart:convert';
import 'package:encrypt/encrypt.dart';

// AES 密钥和 IV（与 JS 保持一致）
final key = Key.fromUtf8('88a26f94e6564bdq'); // 16字节
final iv = IV.fromUtf8('9d43e34e87aa2310'); // 16字节

class CryptoUtil {
  /// 加密（对应 encryptData）
  static String encryptData(dynamic data) {
    final plainText = jsonEncode(data);
    final encrypter = Encrypter(AES(key, mode: AESMode.cbc, padding: 'PKCS7'));
    final encrypted = encrypter.encrypt(plainText, iv: iv);
    return encrypted.base64;
  }

  /// 解密（对应 decryptData）
  static String? decryptData(String? encryptedText) {
    if (encryptedText == null || encryptedText.isEmpty) return null;
    try {
      final encrypter = Encrypter(
        AES(key, mode: AESMode.cbc, padding: 'PKCS7'),
      );
      final decrypted = encrypter.decrypt64(encryptedText, iv: iv);
      return decrypted;
    } catch (e) {
      return null;
    }
  }
}
